<?php
/* MyMeeting is an online meeting management software.
 * Copyright (C) 2009 Government Of Malaysia
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * @author: Abdullah Zainul Abidin, Nuhaa All Bakry, Teow Jit Huan, Tan Chin Voon
 *
 */

class Attendance extends AppModel {
    var $name = "Attendance";
    var $belongsTo = array("Meeting","User");
    
    function saveInvitees($meetingid,$old,$new,$userid=null,$formdata=array()) {
        $this->curUser=$userid;
        $this->Hash->curUser=$userid;
        $this->Meeting->curUser=$userid;
        $remove = array_diff($old,$new); // TO REMOVE
        $add = array_diff($new,$old); // TO ADD
        App::import('Model','Meeting');
        $this->Meeting=& ClassRegistry::init('Meeting');
        App::import('Model','Hash');
        $this->Hash=& ClassRegistry::init('Hash');
        
        $meeting = $this->Meeting->findById($meetingid);
        if (!empty($remove)) {
            $r = $this->find('all',array('conditions'=>array('meeting_id'=>$meetingid,'user_id'=>$remove)));
            foreach ($r as $rval) { 
                $s = $this->findById($rval['Attendance']['id']);
                $s['Attendance']['attend_as'] = isset($formdata[$s['Attendance']['user_id']]);
                $s['Attendance']['deleted'] = 1;
                $s['Attendance']['deleted_date'] = date('Y-m-d H:i:s');
                $this->save($s);
                
                // remove from hash
                $this->Hash->removeData('confirm',$rval['Attendance']['id']);
            }
        }
        if (!empty($add)) {
            foreach ($add as $val) {
                $r = $this->find('first',array('conditions'=>array('meeting_id'=>$meetingid,'user_id'=>$val)));
                if ($r) { // already have record here -> change deleted => 0
                    if ($r['Attendance']['deleted'] == '1') $r['Attendance']['deleted'] = 0;
                    $r['Attendance']['deleted_date'] = '0000-00-00 00:00:00';
                    $r['Attendance']['attend_as'] = $formdata['AttendAs'][$r['Attendance']['user_id']];
                    $this->save($r);
                    $e[0]['Attendance']['id'] = $r['Attendance']['id'];
                } else { // no record -> add new
                    $this->create();
                    $data['meeting_id'] = $meetingid;
                    $data['user_id'] = $val;
                    $data['attend_as'] = $formdata['AttendAs'][$val];
                    $data['created'] = date('Y-m-d H:i:s');
                    $this->save($data);
                    $e[0]['Attendance']['id'] = $this->id;
                }
                
                // save into hash
                $e[0]['Meeting']['meeting_date'] = $meeting['Meeting']['meeting_date'];
                $this->Hash->insertToHashTable('confirm',$e);
            }
        }
    }
    
    function saveData($data) {
        $m = $this->findAllByMeetingId($data['Meeting']['id']);
        // confirmation
        $old = array();
        foreach ($m as $key=>$val) {
            $old['Attendance'][$val['Attendance']['user_id']]['will_attend'] = $val['Attendance']['will_attend'];
            $old['Attendance'][$val['Attendance']['user_id']]['attended'] = $val['Attendance']['attended'];
            $old['Attendance'][$val['Attendance']['user_id']]['excuse'] = $val['Attendance']['excuse'];
            $old['Attendance'][$val['Attendance']['user_id']]['id'] = $val['Attendance']['id'];
        }

        foreach ($data['Attendance'] as $key=>$val) {
      
            // compare with old data
            if (
            //will attend have value and not same with old value
				($val['will_attend']!='' && $val['will_attend'] != $old['Attendance'][$key]['will_attend']) 
				//attended have value and not same with old value
				|| ($val['attended']!='' && $val['attended'] != $old['Attendance'][$key]['attended'])
			){
                $att = $this->findById($val['id']);
                
                if (!empty($val['rep_name']) && $data['Meeting']['allow_rep'] == '1' && $val['will_attend']=='0' ) {
                    $val['will_attend'] = '2'; // set to not attend but send a rep
                }
                //change will attend data
                
                $att['Attendance']['will_attend'] = $val['will_attend'];
                $att['Attendance']['confirm_date'] = date('Y-m-d H:i:s');
                
                if($val['attended']!=null){
					if (!empty($val['rep_name']) && $data['Meeting']['allow_rep'] == '1' && $val['attended']=='0') {
						$val['attended'] = '2'; // set to not attend but send a rep
					} 
                //change attended data
					$att['Attendance']['attended'] = $val['attended'];
					$att['Attendance']['att_updated'] = date('Y-m-d H:i:s');
				}
                
                if ($val['attended']=='1' ||($val['will_attend'] == '1' && empty($val['attended']) && $val['attended']!='0'))
                {
					$att['Attendance']['rep_name'] = null;
					$att['Attendance']['excuse'] = null;
			    }	
			    else
			    {
					if (isset($val['rep_name']) && !empty($val['rep_name'])) 
						$att['Attendance']['rep_name'] = $val['rep_name']; 
					if (isset($val['rep_name']) && !empty($val['excuse'])) 
						$att['Attendance']['excuse'] = $val['excuse']; 
				}
                $this->save($att);
            }

        }
    }
    
    function saveAttendAs($data,$meeting_id) {
        foreach ($data['User']['User'] as $val) {
            if ($val) {
                $r = $this->find('first',array('fields'=>array('*'),'conditions'=>array('meeting_id'=>$meeting_id,'user_id'=>$val))); 
                App::import('Model','Hash');
                $this->Hash=& ClassRegistry::init('Hash');
                if (!$r) {
                    $r = $this->create();
                    $r['Attendance']['user_id'] = $val; 
                    $r['Attendance']['meeting_id'] = $meeting_id; 
                }
                $r['Attendance']['confirm_duedate']=(!empty($data['Meeting']['confirm_duedate']) && $data['Meeting']['confirm_duedate'] != '0000-00-00' && $data['Meeting']['confirm_duedate'] != '1970-01-01')?date('Y-m-d H:i:s',strtotime($data['Meeting']['confirm_duedate'])):$this->Hash->due_date($data['Meeting']['meeting_date']);
                $r['Attendance']['attend_as'] = $data['User']['AttendAs'][$val]; 
                $r['Attendance']['created'] = date('Y-m-d H:i:s'); 
                $this->save($r);
            } 
        }
    }
    
    function updateAttendance($old,$data,$meeting_id){
        App::import('Model','Hash');
        $this->Hash=& ClassRegistry::init('Hash');
        $o_user=array_filter(Set::extract($old,'{n}.Attendance.user_id'));
        $n_user=array_filter($data['User']['User']);
        $invited=array_diff($n_user,$o_user);
        $deleted=array_diff($o_user,$n_user);
        $edited=array_intersect($o_user,$n_user);
        
        if(!empty($edited)){
            foreach ($edited as $e){
                $dkey=array_values(array_filter(array_keys($o_user,$e)));
                if(!empty($dkey)){
                    foreach($dkey as $key){
                        $new['Attendance']=$old[$key]['Attendance'];
                    }
                }else{
                    $new['Attendance']=$old[0]['Attendance'];
                }
                $new['Attendance']['confirm_duedate']=(!empty($data['Meeting']['confirm_duedate']) && $data['Meeting']['confirm_duedate'] != '0000-00-00' && $data['Meeting']['confirm_duedate'] != '1970-01-01')?date('Y-m-d H:i:s',strtotime($data['Meeting']['confirm_duedate'])):$this->Hash->due_date($data['Meeting']['meeting_date']);
                $new['Attendance']['attend_as'] = $data['User']['AttendAs'][$e]; 
                $new['Attendance']['created'] = date('Y-m-d H:i:s'); 
                //debug($new);
                $this->save($new);
                
            }
        }
        if(!empty($deleted)){
            foreach ($deleted as $d){
                $dkey=array_keys($o_user,$d);
                if(!empty($dkey)){
                    foreach($dkey as $key){
                        $this->delete($old[$key]['Attendance']['id']);
                    }
                }
            }
        }
        if(!empty($invited)){
            foreach ($invited as $i) {
                $r = $this->create();
                $r['Attendance']['user_id'] = $i; 
                $r['Attendance']['meeting_id'] = $meeting_id; 
                $r['Attendance']['confirm_duedate']=(!empty($data['Meeting']['confirm_duedate']) && $data['Meeting']['confirm_duedate'] != '0000-00-00' && $data['Meeting']['confirm_duedate'] != '1970-01-01')?date('Y-m-d H:i:s',strtotime($data['Meeting']['confirm_duedate'])):$this->Hash->due_date($data['Meeting']['meeting_date']);
                $r['Attendance']['attend_as'] = $data['User']['AttendAs'][$i]; 
                $r['Attendance']['created'] = date('Y-m-d H:i:s'); 
                $this->save($r);
            } 
        }
        $null=$this->find('all',array('conditions'=>array('meeting_id'=>$meeting_id,'attend_as'=>null)));
        foreach($null as $n){
            $this->delete($n['Attendance']['id']);
        }
    }
    
    //check whether the user is secretariat or not?
    function isSecretariat($meeting_id,$user_id){
        $this->unbindmodel(array('belongsTo'=>array("Meeting")),false);
        $r = $this->find('first',array('field'=>'Attendance.attend_as','conditions'=>array('meeting_id'=>$meeting_id,'user_id'=>$user_id)));   
        if ($r['Attendance']['attend_as'] == 1){return true;}
        else {return false;}
    }
    
    
    function getChairperson($meeting_id){
        $this->User->recursive=0;
        $r = $this->find('first',array('conditions'=>array('meeting_id'=>$meeting_id,'attend_as'=>'2')));
        if ($r) {
            $t = $this->User->find('first',array('conditions'=>array('User.id'=>$r['User']['id'],'Title.id'=>$r['User']['title_id'])));
            return array_merge($r,$t);
        
        } else return false;
    }
    
    //find all the meeting user who can approve the minute
    function getApprover($meeting){
        $r=array();
        $role_approve=array();
        $this->Meeting->Committee->Membership->Role->recursive=-1;
        $role=$this->Meeting->Committee->Membership->Role->find('all',array('conditions'=>array('Role.committee_id'=>array(0,$meeting['Meeting']['committee_id']))));
        foreach($role as $rkey=>$ro){
            $this->Wfmodel=& ClassRegistry::init('Wfmodel');
            $committee_role=$this->Wfmodel->committee_role($meeting['Meeting']['committee_id'],$ro['Role']['id']);
            if(!empty($committee_role['Minute approval']['Create'])){
                $role_approve[]=$ro['Role']['id'];
            }
        }
        if(!empty($role_approve)){
            foreach($role_approve as $ra){
                $member=$this->Meeting->Committee->Membership->find('all',array('conditions'=>array('Membership.role_id'=>$ra,'Membership.committee_id'=>$meeting['Meeting']['committee_id'])));
            }
        }
        if(!empty($member)){
            $user_id=set::extract($member,'{n}.Membership.user_id');
            $r = $this->find('all',array('conditions'=>array('meeting_id'=>$meeting['Meeting']['id'],'user_id'=>$user_id)));
        }
        if(!empty($r)){
            $this->User->recursive=0;
            foreach($r as $rk=>$rd){
                $t = $this->User->find('first',array('conditions'=>array('User.id'=>$rd['User']['id'],'Title.id'=>$rd['User']['title_id'])));
                $r[$rk]=array_merge($rd,$t);
            }
        }
        
        //add in chairperson
        $chairperson=$this->getChairperson($meeting['Meeting']['id']);
        if(!in_array($chairperson['User']['id'],set::extract($r,'{n}.User.id'))){
            $r[]=$chairperson;
        }
        
        return $r;
        
    }
    
    //simple meeting member with attend_as
    function getMember($meeting_id,$attend_as){
        $this->User->recursive=0;
        $r = $this->find('all',array('conditions'=>array('meeting_id'=>$meeting_id,'attend_as'=>$attend_as)));
        if ($r) {
            return $r;
        } else return false;
    }
    
    //check no. of ChairPerson 
    function CheckChairperson($data){
        $users=array_filter(array_values($data['User']));
        $chairperson=0;
        if(!empty($users)){
            foreach($users as $user){
                if($data['AttendAs'][$user]==2){
                    ++$chairperson;
                }
            }
        }
        return $chairperson;
    }
    
    //check no. of secretariat
    function CheckSecretariat($data){
        $users=array_filter(array_values($data['User']));
        $secretariat=0;
        if(!empty($users)){
            foreach($users as $user){
                if($data['AttendAs'][$user]==1){
                    ++$secretariat;
                }
            }
        }
        return $secretariat;
    }
    
    function user_attendance($user_id,$will_attend=null){
        
        $att=$this->find('all',array('fields'=>array('Attendance.id','Meeting.meeting_date','Meeting.meeting_title','Meeting.meeting_num','Meeting.committee_id'),'conditions'=>array('user_id'=>$user_id,'will_attend'=>$will_attend),'contain'=>array('Meeting'=>array('conditions'=>array('Meeting.deleted'=>0)))));
        
        foreach($att as $key=>$a){
            if(date("Y/m/d",strtotime($a['Meeting']['meeting_date'])) < date("Y/m/d",mktime())){
                unset($att[$key]);
            }else{
                $this->Hash=& ClassRegistry::init('Hash');
                $att[$key]['Hash']=$this->Hash->find('first',array('fields'=>array('hash'),'conditions'=>array('foreign_key'=>$a['Attendance']['id'])));
            }
        }
        return $att;
    }
    
    function getAttendees($CommitteeId,$meetingid,$attend=1){
        $options['joins'] = array(
            array('table' => 'memberships',
                'alias' => 'Membership',
                'type' => 'INNER',
                'conditions' => array(
                    'Attendance.user_id = Membership.user_id',
                    'Membership.committee_id='.$CommitteeId
                )
            ),
            array('table' => 'users',
                'alias' => 'User_2',
                'type' => 'LEFT',
                'conditions' => array(
                    'Attendance.user_id = User_2.id',
                )
            ),
            array('table' => 'titles',
                'alias' => 'Title',
                'type' => 'LEFT',
                'conditions' => array(
                    'User_2.title_id = Title.id',
                )
            )
        );

        if ($attend) {
            $options['conditions'] = array(
                'Attendance.attended' => 1,
                'Attendance.meeting_id'=>$meetingid
            );
        } else {
            $options['conditions'] = array(
                'Attendance.attended' =>0,
                'Attendance.meeting_id'=>$meetingid
            );
        }
        $options['fields'] = array('User.*','Attendance.attend_as,Title.short_name');
        $options['order'] = array('Membership.order_id ASC');

        $att = $this->find('all', $options);
        if(empty($attend)){
			$options['conditions'] = array(
                'Attendance.attended' =>null,
                'Attendance.meeting_id'=>$meetingid
            );
            $att2=$this->find('all', $options);
            $att=array_merge($att,$att2);
			
		}
        if (count($att)) return $att;
        else return false;
    }
    
}
?>
